import React, { useState, useEffect } from "react";
import { Button } from "antd";

const Top = (props) => {
  // 全屏展示
  const [full, setFull] = useState(false); // 创建管理是否全屏状态
  const [scre, setScre] = useState("全屏"); // 按钮文字

  const fullScreenHandle = () => {
    const app = document.querySelector(".full-screen"); // 获取App
    if (!full) {
      setScre("退出全屏");
      setFull(true);
      app.requestFullscreen()
       .catch((err) => {
          console.error("请求全屏失败:", err);
        });
    } else {
      setScre("全屏");
      setFull(false);
      document.exitFullscreen()
       .catch((err) => {
          console.error("退出全屏失败:", err);
        });
    }
  };

  const bindKeyDownListener = () => {
    const handleKeyDown = (e) => {
      console.log(e);
      
      if (e.key === "Escape" && full) {
        e.preventDefault();
        // 尝试聚焦一个元素来激活文档
        const targetElement = document.querySelector(".full-screen");
        if (targetElement) {
          targetElement.focus();
        }
        setScre("全屏");
        setFull(false);
        document.exitFullscreen()
         .catch((err) => {
            console.error("退出全屏失败:", err);
          });
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  };

  useEffect(() => {
    console.log("useEffect 执行，开始绑定 keydown 事件监听器");
    const cleanup = bindKeyDownListener();
    return () => {
      console.log("组件卸载，移除 keydown 事件监听器");
      cleanup();
    };
  }, []);

  return (
    <div className="top">
      {/* <Button
        className="screen"
        onClick={() => {
          fullScreenHandle();
        }}
      >
        {scre}
      </Button> */}
      <div
        className="full-screen"
        style={{ backgroundColor: "pink" }}
        onDoubleClick={fullScreenHandle}
      >
        1111122
      </div>
    </div>
  );
};

export default Top;